package com.zhangshuo.patternDesign.composite;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * Created by shuo.zhang on 2017-10-27.
 */
public class Folder extends AbstractFile {
    public Folder(String name) {
        this(name, null);
    }

    public Folder(String name, AbstractFile parent) {
        super(name, parent);
        files = new ArrayList<>();
    }

    private List<AbstractFile> files;

    @Override
    void deleteFile() {
        System.out.println("开始删除文件夹:" + super.getName());
 /*       files.stream().forEach((file) -> {
            file.deleteFile();
            //files.remove(file);
        });*/
        ListIterator<AbstractFile> iterator =files.listIterator();
        AbstractFile fileTemp ;
        while(iterator.hasNext()){
            fileTemp = iterator.next();
            fileTemp.deleteFile();
            iterator.remove();
        }
       if (getParent() != null) {
           System.out.println(getParent().getName() +":" + super.getName());
            getParent().deleteFile(super.getName());
        }
    }

    @Override
    void deleteFile(String name) {
        ListIterator<AbstractFile> iterator =files.listIterator();
        AbstractFile fileTemp ;
        while(iterator.hasNext()){
            fileTemp = iterator.next();
            if(fileTemp.getName().equalsIgnoreCase(name)){
                //fileTemp.deleteFile();
                iterator.remove();
                break;
            }
        }

    }

    @Override
    void addFile(String name) {
        if (name == null)
            name = "";
        if (name.indexOf(".") > -1)
            files.add(new File(name, this));
        else
            files.add(new Folder(name, this));

    }

    @Override
    void display(String prefix) {
        System.out.println(prefix + super.getName());
        //forEach语法
        files.forEach((file) ->
                file.display(prefix + "\t")
        );
    }

    @Override
    AbstractFile getFile(int index) {
        if (index < 0 || files.size() == 0)
            index = 0;
        else if (index > files.size() - 1)
            index = files.size() - 1;
        return files.get(index);
    }
}
